/**
 * 图片压缩工具
 */
export async function compressImage(
  file: File,
  maxWidth: number = 1920,
  maxHeight: number = 1920,
  quality: number = 0.8
): Promise<File> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    
    reader.onload = (event) => {
      const img = new Image()
      img.src = event.target?.result as string
      
      img.onload = () => {
        const canvas = document.createElement('canvas')
        let { width, height } = img

        // 等比例缩放
        if (width > maxWidth || height > maxHeight) {
          const ratio = Math.min(maxWidth / width, maxHeight / height)
          width *= ratio
          height *= ratio
        }

        canvas.width = width
        canvas.height = height

        const ctx = canvas.getContext('2d')!
        
        // 使用高质量缩放
        ctx.imageSmoothingEnabled = true
        ctx.imageSmoothingQuality = 'high'
        ctx.drawImage(img, 0, 0, width, height)

        canvas.toBlob(
          (blob) => {
            if (blob) {
              const compressed = new File([blob], file.name, {
                type: 'image/jpeg',
                lastModified: Date.now()
              })
              resolve(compressed)
            } else {
              reject(new Error('压缩失败'))
            }
          },
          'image/jpeg',
          quality
        )
      }
      
      img.onerror = () => reject(new Error('图片加载失败'))
    }
    
    reader.onerror = () => reject(new Error('文件读取失败'))
  })
}

/**
 * 检测 WebP 支持
 */
export function supportsWebP(): boolean {
  const canvas = document.createElement('canvas')
  canvas.width = canvas.height = 1
  return canvas.toDataURL('image/webp').indexOf('image/webp') === 0
}

/**
 * 转换为 WebP
 */
export async function convertToWebP(file: File, quality: number = 0.9): Promise<File> {
  if (!supportsWebP()) {
    return file
  }

  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')!
  const img = new Image()

  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    
    reader.onload = (e) => {
      img.src = e.target?.result as string
      
      img.onload = () => {
        canvas.width = img.width
        canvas.height = img.height
        ctx.drawImage(img, 0, 0)

        canvas.toBlob(
          (blob) => {
            if (blob) {
              const webpFile = new File(
                [blob],
                file.name.replace(/\.\w+$/, '.webp'),
                { type: 'image/webp', lastModified: Date.now() }
              )
              resolve(webpFile)
            } else {
              reject(new Error('转换失败'))
            }
          },
          'image/webp',
          quality
        )
      }
      
      img.onerror = () => reject(new Error('图片加载失败'))
    }
    
    reader.onerror = () => reject(new Error('文件读取失败'))
  })
}

/**
 * 获取图片尺寸
 */
export async function getImageDimensions(file: File): Promise<{ width: number; height: number }> {
  return new Promise((resolve, reject) => {
    const img = new Image()
    const url = URL.createObjectURL(file)
    
    img.onload = () => {
      URL.revokeObjectURL(url)
      resolve({
        width: img.width,
        height: img.height
      })
    }
    
    img.onerror = () => {
      URL.revokeObjectURL(url)
      reject(new Error('无法读取图片尺寸'))
    }
    
    img.src = url
  })
}

/**
 * 生成缩略图
 */
export async function generateThumbnail(
  file: File,
  size: number = 200
): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    
    reader.onload = (event) => {
      const img = new Image()
      img.src = event.target?.result as string
      
      img.onload = () => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')!
        
        // 计算缩略图尺寸（保持比例）
        let width = img.width
        let height = img.height
        
        if (width > height) {
          if (width > size) {
            height = (height / width) * size
            width = size
          }
        } else {
          if (height > size) {
            width = (width / height) * size
            height = size
          }
        }
        
        canvas.width = width
        canvas.height = height
        ctx.drawImage(img, 0, 0, width, height)
        
        resolve(canvas.toDataURL('image/jpeg', 0.7))
      }
      
      img.onerror = () => reject(new Error('生成缩略图失败'))
    }
    
    reader.onerror = () => reject(new Error('文件读取失败'))
  })
}

/**
 * 验证图片文件
 */
export function validateImageFile(file: File): { valid: boolean; error?: string } {
  const validTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif']
  const maxSize = 10 * 1024 * 1024 // 10MB

  if (!validTypes.includes(file.type)) {
    return {
      valid: false,
      error: '不支持的文件格式。请上传 JPG、PNG、WebP 或 GIF 图片。'
    }
  }

  if (file.size > maxSize) {
    return {
      valid: false,
      error: `文件大小不能超过 ${maxSize / 1024 / 1024}MB`
    }
  }

  return { valid: true }
}

